<?php

namespace app\admin\model;

use think\Model;


class Userbalance extends Model
{


    // 表名
    protected $name = 'user_balance';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'create_time_text'
    ];


    public function getTypeList()
    {
        return ['in' => __('收入'), 'out' => __('支出')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shop()
    {
        return $this->belongsTo('Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function balance($shop_id, $user_id)
    {

        if($shop_id == -1){
            $in = $balance = $this->where('type', 'in')->where('user_id', $user_id)->sum('amount');
            $out = $balance = $this->where('type', 'out')->where('user_id', $user_id)->sum('amount');

        }else{
            $in = $balance = $this->where('type', 'in')->where('shop_id', $shop_id)->where('user_id', $user_id)->sum('amount');
            $out = $balance = $this->where('type', 'out')->where('shop_id', $shop_id)->where('user_id', $user_id)->sum('amount');

        }

        return $in - $out;
    }
}
